//
//  JTNetInfoUntil.swift
//  JT Center
//
//  Created by 林殊 on 2021/5/27.
//  Copyright © 2021 J&T Express. All rights reserved.
//

import UIKit
import CoreTelephony

public class JTNetInfoUntil: NSObject {
    
    /// 传网络请求的 Baseurl
    public static func presentViewController(baseUrl: String) {
        let url = "https://download.jtexpress.com.cn/h5/phoneInfo/index.html"
        let dict = ["userAgent": modelName,
                    "platform":platform(),
                    "phoneType": "PhoneType: \(modelName)",
                    "appVersion": appVersion(),
                    "outIp": getWANIPAddress(),
                    "domainIp": urlIpAddress(str: baseUrl),
                    "isp": getCarrierInfo()]
        let data = self.toJSONString(dict: dict)
        let qureitem = URLQueryItem(name: "data", value: data)
        let regUrl = NSURLComponents(string: url)!
        regUrl.queryItems = [qureitem]
        let nav = UINavigationController(rootViewController: JTNetInfoViewController(regUrl.url))
        nav.modalPresentationStyle = .fullScreen
        UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
    }
    
    //操作系统
    static func platform() -> String {
        let system = UIDevice.current.systemName
        let version = UIDevice.current.systemVersion
        return   system + " " + version
    }
    
    //手机类型 -- 获取设备型号
    static func phoneType() -> String {
        return UIDevice.current.model
    }
    
    //获取app版本
    static func appVersion() -> String {
        let appV = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
        let appB = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
        return "AppVersion: \(appV)(Build \(appB))"
    }
    
    //获取设备型号
    static var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        
        print(identifier)
        switch identifier {
        case "iPod5,1":                                 return "iPod Touch 5"
        case "iPod7,1":                                 return "iPod Touch 6"
        case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
        case "iPhone4,1":                               return "iPhone 4s"
        case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
        case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
        case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
        case "iPhone7,2":                               return "iPhone 6"
        case "iPhone7,1":                               return "iPhone 6 Plus"
        case "iPhone8,1":                               return "iPhone 6s"
        case "iPhone8,2":                               return "iPhone 6s Plus"
        case "iPhone9,1":                               return "iPhone 7 (CDMA)"
        case "iPhone9,3":                               return "iPhone 7 (GSM)"
        case "iPhone9,2":                               return "iPhone 7 Plus (CDMA)"
        case "iPhone9,4":                               return "iPhone 7 Plus (GSM)"
        case "iPhone10,1":                              return "iPhone 8"
        case "iPhone10,2":                              return "iPhone 8 Plus"
        case "iPhone10,3":                              return "iPhone X"
        case "iPhone10,4":                              return "iPhone 8"
        case "iPhone10,5":                              return "iPhone 8 Plus"
        case "iPhone10,6":                              return "iPhone X"
        case "iPhone11,2":                              return "iPhone XS"
        case "iPhone11,4":                              return "iPhone XS Max"
        case "iPhone11,6":                              return "iPhone XS Max CN"
        case "iPhone11,8":                              return "iPhone XR"
        case "iPhone12,1":                              return "iPhone 11"
        case "iPhone12,3":                              return "iPhone 11 Pro"
        case "iPhone12,5":                              return "iPhone 11 Pro Max"
        case "iPhone12,8":                              return "iPhone SE (2nd generation)"
        case "iPhone13,1":                              return "iPhone 12 mini"
        case "iPhone13,2":                              return "iPhone 12"
        case "iPhone13,3":                              return "iPhone 12 Pro"
        case "iPhone13,4":                              return "iPhone 12 Pro Max"
            
        case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
        case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
        case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
        case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
        case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
        case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
        case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
        case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
        case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
        case "iPad6,7", "iPad6,8":                      return "iPad Pro"
        case "AppleTV5,3":                              return "Apple TV"
        case "i386", "x86_64":                          return "Simulator"
        default:                                        return identifier
        }
    }
    
    //获取某个网址的ip
    static func urlIpAddress(str: String) -> String {
        
        guard let url = URL(string: str) else { return "" }
        let arr = self.urlToIP_gethostbyname(url)
        if arr.count > 0 {
            return arr[0]
        } else {
            return ""
        }
    }
    
    private static func urlToIP_gethostbyname(_ url: URL) -> [String] {
        var ipList: [String] = []
        guard let hostname = url.host else {
            return ipList
        }
        guard let host = hostname.withCString({ gethostbyname($0) }) else {
            return ipList
        }
        guard host.pointee.h_length > 0 else {
            return ipList
        }
        var index = 0
        while host.pointee.h_addr_list[index] != nil {
            var addr = in_addr()
            memcpy(&addr.s_addr, host.pointee.h_addr_list[index], Int(host.pointee.h_length))
            guard let remoteIPAsC = inet_ntoa(addr) else {
                return ipList
            }
            ipList.append(String(cString: remoteIPAsC))
            index += 1
        }
        print(ipList)
        return ipList
    }
    
    //获取外网IP
    static func getWANIPAddress() -> String {
        guard let ipUrl = URL(string: "https://api64.ipify.org?format=json") else { return "" }
        let ip = try? NSMutableString(contentsOf: ipUrl, encoding: String.Encoding.utf8.rawValue)
        let data = Data((ip as! String).utf8)
        let dict = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
        let info = (dict as? [String: Any] ?? [String: Any]())
        let cip = info["ip"] as? String ?? ""
        return cip
        
    }
    
    
    //网络运营商
    static func getCarrierInfo() -> String {
        let tele = CTTelephonyNetworkInfo()
        let code = tele.subscriberCellularProvider?.mobileNetworkCode
        switch code {
        case "00","02", "07":
            return "China Mobile"
        case "01","06":
            return "China Unicom"
        case "03","05":
            return "China Telecom"
        default:
            return "unknown"
        }
    }
    
    ///字典转json
    static func toJSONString(dict: [String: Any]) -> String {
        let dict = dict as NSDictionary
        if (!JSONSerialization.isValidJSONObject(dict)) {
            print("")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dict, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
}
